const examApi = require('../../utils/examApi.js');

Page({
  data: {
    examId: null,
    totalQuestions: 0,
    currentIndex: 0,
    selectedOption: '',
    showCard: false,
    timer: null,
    remainingTime: 3600, // 默认1小时
    formatTime: '00:00:00',
    questions: [],
    currentQuestion: {},
    mode: 'exam',
    examTitle: '',
    isSubmitting: false,
    loading: true,
    examDuration: 120 // 默认考试时长（分钟）
  },

  onLoad(options) {
    if (options.examId) {
      this.setData({
        examId: options.examId,
        loading: true
      });
      this.loadExamInfo();
    } else {
      wx.showToast({
        title: '试卷ID不能为空',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  async loadExamInfo() {
    try {
      console.log('开始加载试卷信息，examId:', this.data.examId);
      
      // 获取试卷信息
      const examPaper = await examApi.getExamPaperDetail(this.data.examId);
      console.log('获取到的试卷信息:', examPaper);
      
      // 获取试题列表
      const questions = await examApi.getExamQuestions(this.data.examId);
      console.log('获取到的原始题目列表:', questions);
      
      // 格式化题目数据
      const formattedQuestions = questions.map(q => {
        const formatted = {
          id: q.id,
          type: this.mapQuestionType(q.questionType),
          content: q.content,
          options: JSON.parse(q.options || '{}'),
          correctAnswer: q.correctAnswer,
          analysis: q.analysis,
          answered: false,
          userAnswer: ''
        };
        console.log('格式化后的题目:', formatted);
        return formatted;
      });

      console.log('所有格式化后的题目:', formattedQuestions);
      console.log('第一道题目:', formattedQuestions[0]);

      this.setData({
        examTitle: examPaper.title,
        questions: formattedQuestions,
        totalQuestions: formattedQuestions.length,
        currentQuestion: formattedQuestions[0] || {},
        remainingTime: examPaper.duration * 60,
        examDuration: examPaper.duration,
        loading: false
      }, () => {
        console.log('数据更新后的状态:', {
          examTitle: this.data.examTitle,
          totalQuestions: this.data.totalQuestions,
          currentQuestion: this.data.currentQuestion,
          remainingTime: this.data.remainingTime,
          examDuration: this.data.examDuration
        });
      });

      // 开始计时
      this.startTimer();
    } catch (error) {
      console.error('加载试卷信息失败:', error);
      console.error('错误详情:', {
        message: error.message,
        stack: error.stack
      });
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  mapQuestionType(type) {
    const typeMap = {
      'SINGLE_CHOICE': 'single',
      'MULTIPLE_CHOICE': 'multiple',
      'JUDGMENT': 'judgment'
    };
    return typeMap[type] || 'single';
  },

  startTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }

    const timer = setInterval(() => {
      if (this.data.remainingTime <= 0) {
        clearInterval(timer);
        this.submitAnswers();
        return;
      }

      const remainingTime = this.data.remainingTime - 1;
      const formatTime = this.formatTime(remainingTime);
      
      this.setData({
        remainingTime,
        formatTime
      });
    }, 1000);

    this.setData({ timer });
  },

  formatTime(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  },

  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  async submitAnswers() {
    if (this.data.isSubmitting) {
      return;
    }
    
    this.setData({
      isSubmitting: true
    });
    
    console.log('开始提交答案');
    
    wx.showLoading({
      title: '正在提交...',
      mask: true
    });
    
    // 停止计时
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    
    try {
      // 收集答题数据
      const answers = {};
      this.data.questions.forEach(q => {
        if (q.userAnswer) {
          answers[q.id] = q.userAnswer;
        }
      });

      // 获取用户信息
      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo) {
        throw new Error('未获取到用户信息');
      }

      // 计算答题时长（分钟）
      const spentTime = this.data.examDuration * 60 - this.data.remainingTime; // 已用时间（秒）
      const duration = Math.ceil(spentTime / 60); // 转换为分钟并向上取整
      
      console.log('提交数据:', {
        userId: parseInt(userInfo.id),
        paperId: parseInt(this.data.examId),
        answers,
        duration
      });

      // 提交答案
      const result = await examApi.submitExam(
        parseInt(userInfo.id),
        parseInt(this.data.examId),
        answers,
        duration
      );

      // 计算正确率
      const correctCount = this.data.questions.filter(q => q.userAnswer === q.correctAnswer).length;
      const correctRate = Math.round((correctCount / this.data.totalQuestions) * 100);

      // 准备结果数据
      const examResult = {
        examId: this.data.examId,
        examTitle: this.data.examTitle,
        totalQuestions: this.data.totalQuestions,
        correctCount,
        wrongCount: this.data.totalQuestions - correctCount,
        correctRate,
        answers: this.data.questions.map(q => ({
          id: q.id,
          userAnswer: q.userAnswer || '',
          correct: q.userAnswer === q.correctAnswer,
          correctAnswer: q.correctAnswer,
          analysis: q.analysis
        })),
        spendTime: duration * 60,
        timestamp: new Date().getTime()
      };

      // 保存结果
      wx.setStorageSync('examResults_' + this.data.examId, examResult);

      wx.hideLoading();
      
      // 跳转到提交结果页
      wx.redirectTo({
        url: `/pages/submit/index?examId=${this.data.examId}`,
        fail: (error) => {
          console.error('跳转失败:', error);
          wx.showToast({
            title: '跳转失败，请重试',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error('提交答案失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '提交失败',
        icon: 'none'
      });
      this.setData({
        isSubmitting: false
      });
    }
  },

  // 选择答案
  selectOption(e) {
    const { option } = e.currentTarget.dataset;
    const questions = this.data.questions;
    const currentIndex = this.data.currentIndex;
    
    // 更新当前题目的答案
    questions[currentIndex].answered = true;
    questions[currentIndex].userAnswer = option;
    
    this.setData({
      questions,
      selectedOption: option
    });

    // 自动跳转到下一题
    setTimeout(() => {
      if (currentIndex < questions.length - 1) {
        this.nextQuestion();
      }
    }, 500);
  },

  // 上一题
  prevQuestion() {
    if (this.data.currentIndex > 0) {
      const newIndex = this.data.currentIndex - 1;
      this.setData({
        currentIndex: newIndex,
        currentQuestion: this.data.questions[newIndex],
        selectedOption: this.data.questions[newIndex].userAnswer || ''
      });
    }
  },

  // 下一题
  nextQuestion() {
    if (this.data.currentIndex < this.data.questions.length - 1) {
      const newIndex = this.data.currentIndex + 1;
      this.setData({
        currentIndex: newIndex,
        currentQuestion: this.data.questions[newIndex],
        selectedOption: this.data.questions[newIndex].userAnswer || ''
      });
    }
  },

  // 切换答题卡显示状态
  toggleCard() {
    this.setData({
      showCard: !this.data.showCard
    });
  },

  // 显示答题卡
  showQuestionCard() {
    this.setData({
      showCard: true
    });
  },

  // 隐藏答题卡
  hideQuestionCard() {
    this.setData({
      showCard: false
    });
  },

  // 跳转到指定题目（与答题卡配合使用）
  goToQuestion(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      currentIndex: index,
      currentQuestion: this.data.questions[index],
      selectedOption: this.data.questions[index].userAnswer || '',
      showCard: false
    });
  }
}); 